package com.xuerhua.yxt.controller.sys.kccs;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.xuerhua.yxt.reqVo.TeacherIdQueryVO;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xuerhua.yxt.common.AdminUser;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.ExcelTemplate;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.excel.CellUtil;
import com.xuerhua.yxt.excel.JxlsExcelView;
import com.xuerhua.yxt.model.KccsCourseInfo;
import com.xuerhua.yxt.model.TeacherInfo;
import com.xuerhua.yxt.reqVo.KccsCourseQueryVO;
import com.xuerhua.yxt.reqVo.KccsCourseReqVO;
import com.xuerhua.yxt.service.IKccsCourseInfoService;
import com.xuerhua.yxt.service.ITeacherService;
import com.xuerhua.yxt.utils.StringUtil;

@RequestMapping("/sys/kccsCourse/manage")
@Controller
public class SysKccsMangeController extends BaseController {
	
	@Autowired
	private IKccsCourseInfoService kccsCourseInfoService;
	@Autowired
	private ITeacherService teacherService;
	
	@RequestMapping(value={"","/"})
	public String Index() {
		return "sys/kccsCourse/manage";
	}
	
	@RequestMapping("pageQuery")
	@ResponseBody Object pageQuery(KccsCourseQueryVO vo){
		try {
			vo.setTermId(getCurrentTerm().getId());
			return kccsCourseInfoService.selectListByPage(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("addUpdate")
	@ResponseBody Object addUpdate(KccsCourseReqVO vo) {
		try {
			AdminUser user = getAdminUser();
			if(StringUtils.isNotBlank(vo.getClassTeacherIds())) {
				TeacherIdQueryVO teacherIdQueryVO = new TeacherIdQueryVO();
				teacherIdQueryVO.setSchoolId(vo.getSchoolId());
				teacherIdQueryVO.setList(Arrays.asList(vo.getClassTeacherIds().split(",")));
				List<TeacherInfo> list = teacherService.selectListBySchoolidAndIds(teacherIdQueryVO);
				if(StringUtil.isNullOrEmpty(list)) {
					vo.setClassTeacher(vo.getClassTeacherIds());
					vo.setClassTeacherIds(null);
				}else {
					String names = "";
					String ids = "";
					for(int i = 0; i < list.size(); i++) {
						TeacherInfo teacher = list.get(i);
						names += teacher.getName();
						ids += teacher.getId();
						if((i+1) < list.size()){
							names += ",";
							ids += ",";
						}
					}
					vo.setClassTeacher(names);
					vo.setClassTeacherIds(ids);
				}
			}
			if(vo.getId() != null) {
				vo.setUpdaterId(user.getTeacherInfo().getId());
				vo.setUpdateTime(new Date());
			}else {
				vo.setCreaterId(user.getTeacherInfo().getId());
				vo.setApprover(user.getTeacherInfo().getName());
				vo.setIsAgree(1);
			}
			kccsCourseInfoService.addAndUpdate(vo);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("del")
	@ResponseBody Object del(String delIds) {
		try {
			kccsCourseInfoService.delKccsCourse(Arrays.asList(delIds.split(",")));
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("openClass")
	@ResponseBody Object openClass(String courseIds){
		try {
			AdminUser user = getAdminUser();
			List<String> list = Arrays.asList(courseIds.split(","));
			kccsCourseInfoService.updateBatchCourseStatus(list, 1, 
					user.getTeacherInfo().getId(), 
					user.getTeacherInfo().getName(),
					user.getTeacherInfo().getSchoolId());
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("stopClass")
	@ResponseBody Object stopClass(String courseIds){
		try {
			AdminUser user = getAdminUser();
			List<String> list = Arrays.asList(courseIds.split(","));
			kccsCourseInfoService.updateBatchCourseStatus(list, 2, 
					user.getTeacherInfo().getId(), 
					user.getTeacherInfo().getName(),
					user.getTeacherInfo().getSchoolId());
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("export")
	ModelAndView export() {
		ModelAndView modelAndView = new ModelAndView();
		try {
			List<KccsCourseInfo> list = kccsCourseInfoService.selectList(new KccsCourseQueryVO());
			for(int i = 0; i < list.size(); i++) {
				list.get(i).setId(i+1);
			}
			modelAndView.getModelMap().addAttribute("list", list);
			
			JxlsExcelView view = new JxlsExcelView(ExcelTemplate.KCCS_COURSE);
			
			modelAndView.setView(view);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return modelAndView;
	}
	
	@RequestMapping("import")
	@ResponseBody Object courseImport(
			@RequestParam(value="files")MultipartFile buildInfo) {
		try {
			AdminUser user = getAdminUser();
			// 创建一个FileInputStream 文件输入流
	        InputStream inputStream = buildInfo.getInputStream();
	    	// 创建对Excel工作簿文件的引用
	        Workbook wookbook = null;
	        String filename = buildInfo.getOriginalFilename();
	        String fileType = filename.substring(filename.lastIndexOf(".") + 1,
	        		filename.length());
	        if (fileType.equals("xls")) {
	        	try{
	        		wookbook = new HSSFWorkbook(inputStream);
	        	}catch(Exception e){
	        		wookbook = null;
	           	 	wookbook = new XSSFWorkbook(inputStream);
	        	}
	        }else{
	       	 	wookbook = new XSSFWorkbook(inputStream);
	        }
	        // 在Excel文档中，第一张工作表的缺省索引是0
	        Sheet sheet = wookbook.getSheetAt(0);
	        int coloumNum=sheet.getRow(1).getPhysicalNumberOfCells();// 获取总列数
	        int rowNum=sheet.getPhysicalNumberOfRows();//获得总行数
	        if(rowNum <= 2) {
	        	return new RspResult(Status.TEMPLATE_DATA_NULL);
	        }
	        List<KccsCourseInfo> list = new ArrayList<>();
	        List<String> errorList = new ArrayList<>();
	        // 遍历行 从第三行开始遍历
	        for (int i = 2; i < rowNum; i++) {
	        	// 读取左上端单元格
	            Row row = sheet.getRow(i);
	            // 行不为空
	            if (row != null) {
	            	KccsCourseInfo plan = new KccsCourseInfo();
	            	for(int j = 0; j < coloumNum; j ++) {
	            		Cell cell = row.getCell((short)j);
	            		if(cell != null) {
	            			String val = CellUtil.getCellValue(cell);
	            			if(j == 0) {
	            				if(StringUtils.isBlank(val)) {
	            					plan.setCreaterId(user.getTeacherInfo().getId());
	            					plan.setApprover(user.getTeacherInfo().getName());
	            					plan.setIsAgree(1);
	            				}else {
	            					plan.setId(Integer.valueOf(val));
	            					plan.setUpdaterId(user.getTeacherInfo().getId());
	            					plan.setUpdateTime(new Date());
	            				}
	            				continue;
	            			}
	            			if(StringUtils.isBlank(val)) {
	            				errorList.add("第" + (i + 1) + "行第" + (j + 1) + "列的值为空");
	            				break;
	            			}
	            			if(j == 1) plan.setCourseName(val);
	            			else if(j == 2) {
	            				List<TeacherInfo> teacherList = teacherService.selectListByNames(Arrays.asList(val.split(",")));
	            				List<String> ids = new ArrayList<>();
	            				for(TeacherInfo teacherInfo : teacherList) {
	            					ids.add(String.valueOf(teacherInfo.getId()));
	            				}
	            				plan.setClassTeacher(val);
	            				plan.setClassTeacherIds(String.join(",", ids));
	            			}
	            			else if(j == 3) plan.setTeacherDesc(val);
	            			else if(j == 4) plan.setClassAddr(val);
	            			else if(j == 5) plan.setClassDate(val);
	            			else if(j == 6) plan.setLimitNum(Integer.valueOf(val));
	            			else if(j == 7) plan.setTeachingObject(val);
	            			else if(j == 8) plan.setCourseDesc(val);
	            		}
	            	}
	            	plan.setIsAgree(1);
	            	list.add(plan);
	            }
	        }
	        if(!StringUtil.isNullOrEmpty(errorList)) {
	        	return new RspResult(Status.FAIL.getCode(), String.join(",", errorList));
	        }
	        kccsCourseInfoService.updateBatchCourseInfo(list);
	        return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new RspResult(Status.TEMPLATE_ERROR);
	}
	
}
